package press.bolin.game;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

// 主渲染窗体
public class GameFrame extends JFrame {
    // 游戏速度
    private long spd = 1000 / 24; // 每秒24帧

    // 双缓冲
    private Image offScreenImage = null;


    // 窗口尺寸
    private int windowWidth = 1400;
    private int windowHeight = 700;
    // 背景图
    private Background background = new Background(this);

    private Champion player = new Champion(this);

    public void launch() {
        // 设置尺寸
        setSize(windowWidth, windowHeight);
        // 窗口居中
        setLocationRelativeTo(null);
        // 关闭事件
        setDefaultCloseOperation(3);
        // 用户不能调整窗口大小
        setResizable(false);
        // 标题
        setTitle("KingOfHonor");
        // 窗口可见
        setVisible(true);
        this.addKeyListener(new KeyMonitor());
        // 重绘
        while (true) {
            repaint();
            try {
                Thread.sleep(spd);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 绘图
     *
     * @param g
     */
    @Override
    public void paint(Graphics g) {
        if (offScreenImage == null) {
            offScreenImage = this.createImage(1400, 700);
        }
        Graphics graphics = offScreenImage.getGraphics();
        background.paintSelf(graphics);
        player.paintSelf(graphics);
        // 等整张图片渲染好了，再一次画上去
        // 居中
//        int x = -player.getX() + windowWidth / 3;
//        if (x < 0) {
//            x = 0;
//        }
//        if (x > 1400) {
//            x = 1400;
//        }
//        int y = -player.getY() + windowHeight / 3;
//        if (y < 0) {
//            y = 0;
//        }
//        if (y > 700) {
//            y = 700;
//        }
        g.drawImage(offScreenImage, 0, 0, null);
    }

    /**
     * main
     *
     * @param args
     */
    public static void main(String[] args) {
        GameFrame gameFrame = new GameFrame();
        gameFrame.launch();
    }

    // 键盘操作
    class KeyMonitor extends KeyAdapter {
        // 按下
        @Override
        public void keyPressed(KeyEvent e) {
            player.keyPressed(e);
        }

        // 释放
        @Override
        public void keyReleased(KeyEvent e) {
            player.keyReleased(e);
        }
    }

}
